package com.dycong.common.IO.socket.SSL;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.UnknownHostException;
import java.security.KeyStore;

/**
 * Created by dycong on 2017/3/27.
 */
public class TestSSLSocketClient {
    private static String path = "e:\\keytool\\sslclient.keystore";
    private static char[] password = "aaaaaaa".toCharArray();

    /**
     * @param args
     */
    public static void main(String[] args) {
        SSLContext context = null;
        try {
            KeyStore ts = KeyStore.getInstance("JKS");
            ts.load(new FileInputStream(path), password);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ts);
            TrustManager[] tm = tmf.getTrustManagers();
            context = SSLContext.getInstance("SSL");
            context.init(null, tm, null);
        } catch (Exception e) {         //省略捕获的异常信息
            e.printStackTrace();
        }
        SSLSocketFactory ssf = context.getSocketFactory();
        try {
            SSLSocket ss = (SSLSocket) ssf.createSocket("localhost", 8000);
            System.out.println("客户端就绪。");
            ObjectInputStream br = new ObjectInputStream(ss.getInputStream());
            try {
                System.out.println(br.readObject());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            br.close();
            ss.close();
            System.out.println("客户端测试ok");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
